﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HostsManager.Model
{
    sealed public class Section
    {
        public String Name
        {
            get { return name; }
            set { name = value; }
        }
        private String name;

        public bool Enabled
        {
            get { return enabled; }
            set { enabled = value; }
        }
        private bool enabled;

        /*
        public Dictionary<String, Configuration> Configurations
        {
            get { return configurations; }
        }
        */

        public IEnumerable<Configuration> Configurations
        {
            get
            {
                foreach (var item in this.configurations)
                {
                    yield return item.Value;
                }
            }
        }
        private Dictionary<String, Configuration> configurations;


        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name"></param>
        /// <param name="enabled"></param>
        internal Section(String name, bool enabled)
        {
            this.name = name;
            this.enabled = enabled;

            configurations = new Dictionary<string, Configuration>();
        }

        internal void AddConfiguration(Configuration configuration)
        {
            if (configuration.ParentSection == null)
            {
                configuration.ParentSection = this;
                configurations.Add(configuration.Name, configuration);
            }
            else
                throw new Exception(strings.ConfigurationAlreadyHasParentSection);
        }

        internal void RemoveConfiguration(Configuration configuration)
        {
            configurations.Remove(configuration.Name);
            configuration.ParentSection = null;
        }

        internal Configuration GetConfiguration(string name)
        {
            Configuration configuration = null; 
            configurations.TryGetValue(name, out configuration);
            return configuration;
        }

        internal void DisableAllConfigurations()
        {
            foreach (Configuration c in configurations.Values)
                c.Enabled = false;
        }

        internal string GetUnusedConfigurationName()
        {
            int counter = 0;
            string name;

            do
            {
                ++counter;
                name = "configuration" + counter.ToString().PadLeft(2, '0');
            } while (this.GetConfiguration(name) != null);

            return name;
        }
    }
}
